package com.csap.framework.oauth2.client.user.strategy;

import cn.dev33.satoken.LoginUtil;
import cn.dev33.satoken.config.SaTokenConfig;
import com.csap.framework.extension.result.ResultParam;
import com.csap.framework.oauth2.UserInfo;
import com.csap.framework.oauth2.client.Oauth2ClientProperties;
import com.csap.framework.oauth2.UserInfoMod;
import com.csap.framework.oauth2.FindUserService;
import com.csap.framework.oauth2.type.Oauth2ServerType;
import com.ejlchina.data.TypeRef;
import com.ejlchina.okhttps.OkHttps;
import lombok.AllArgsConstructor;

import java.lang.instrument.Instrumentation;
import java.util.Objects;

/**
 * http模式获取用户信息
 *
 * @author yangchengfu
 * @dataTime 2021年-05月-16日 16:04:00
 **/
@AllArgsConstructor
public class HttpFindUserServiceImpl implements FindUserService {
    private final Oauth2ClientProperties oauth2ClientProperties;
    private final SaTokenConfig saTokenConfig;

    @Override
    public UserInfoMod mod() {
        return UserInfoMod.HTTP;
    }

    @Override
    public UserInfo findByUserId(Object loginId) {
        return findByUserId(loginId, LoginUtil.loginType());
    }

    @Override
    public UserInfo findByUserId() {
        return findByUserId(null, LoginUtil.loginType());
    }

    @Override
    public UserInfo findByUserId(Object loginId, String loginType) {
        return OkHttps.sync(oauth2ClientProperties.getOauth2ServerUrl() + (Objects.nonNull(loginId) ? Oauth2ServerType.userInfoId : Oauth2ServerType.userInfo).getPath())
                .addUrlPara(saTokenConfig.getTokenName(), accessToken())
                .addUrlPara("loginId", loginId)
                .addUrlPara("clientId", oauth2ClientProperties.getClientId())
                .addUrlPara("clientSecret", oauth2ClientProperties.getClientSecret())
                .addHeader(saTokenConfig.getLoginType(), LoginUtil.loginType())
                .get()
                .getBody()
                .toBean(new TypeRef<ResultParam<UserInfo>>() {
                }).getData();
    }
}
